from datetime import datetime
from sqlalchemy import Column, Integer, String, DateTime, Enum, Text, JSON
from sqlalchemy import Boolean  # 单独导入Boolean
from app.extensions import db


class Device(db.Model):
    __tablename__ = 'devices'
    
    id = Column(Integer, primary_key=True)
    device_id = Column(String(50), unique=True, nullable=False)
    device_name = Column(String(100), default='MDK_001')
    firmware_version = Column(String(20))
    status = Column(Enum('online', 'offline', 'maintenance'), default='offline')
    is_locked = Column(Boolean, default=False)  # 添加锁定状态
    battery_level = Column(Integer)  # 电量百分比
    last_heartbeat = Column(DateTime)
    last_user_id = Column(Integer)  # 最后连接的用户
    created_at = Column(DateTime, default=datetime.now)
    
    def to_dict(self):
        return {
            'id': self.id,
            'device_id': self.device_id,
            'device_name': self.device_name,
            'firmware_version': self.firmware_version,
            'status': self.status,
            'is_locked': self.is_locked,  # 添加锁定状态
            'battery_level': self.battery_level,
            'last_heartbeat': self.last_heartbeat.isoformat() if self.last_heartbeat else None,
            'last_user_id': self.last_user_id,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'is_online': self._is_online()
        }
    
    def _is_online(self):
        """判断设备是否在线（5分钟内有心跳）"""
        if not self.last_heartbeat:
            return False
        return (datetime.utcnow() - self.last_heartbeat).total_seconds() < 300
    
    def update_heartbeat(self, battery_level=None, user_id=None):
        """更新设备心跳"""
        self.last_heartbeat = datetime.utcnow()
        self.status = 'online'
        if battery_level is not None:
            self.battery_level = battery_level
        if user_id is not None:
            self.last_user_id = user_id
        db.session.commit()


class DeviceLog(db.Model):
    __tablename__ = 'device_logs'
    
    id = Column(Integer, primary_key=True)
    device_id = Column(String(50), nullable=False)
    user_id = Column(Integer)
    action = Column(String(50))  # connect, disconnect, start_treatment, etc.
    data = Column(JSON)  # 额外数据
    created_at = Column(DateTime, default=datetime.now)
    
    def to_dict(self):
        return {
            'id': self.id,
            'device_id': self.device_id,
            'user_id': self.user_id,
            'action': self.action,
            'data': self.data,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }